<template>
  <view class="update">
  	<view class="update-logo">
  		<image class="img" src="/static/logo.png" mode="aspectFit"></image>
  	</view>
  	<view class="update-prog-wrap">
  		<text class="update-title">{{text}}</text>
  		<view class="update-prog">
  			<progress
  				:percent="upgrade"
  				activeColor="#00374d"
  				stroke-width="8"
  				class="progress"
  			/>
  		</view>
  	</view>
  </view>
</template>

<script>
	export default {
		data() {
			return {
				platform: uni.getSystemInfoSync().platform,//客户端平台，值域为：ios、android
				updateText: '正在检查更新，请稍等',
				upgrade: 0,
				sVersion: '',
				update: '',
				statu: true
			};
		},
    computed: {
      text () {
        console.log(this.updateText);
        return this.updateText
      },
    },
		onShow () {
			this.update = uni.getStorageSync('update')
			uni.removeStorageSync('update')
			// #ifdef APP-PLUS
				this.checkUpdates(this.update)
			// #endif
		},
		methods: {
			checkUpdates (info) {
				/*
				 * 检查更新
				 * 1、检查本地缓存版本号
				 * sVersion storage 本地缓存版本
				 * mVersion manifest.json 版本
				*/
				const sVersion = plus.storage.getItem('sVersion');

				if (!sVersion) {
					this.getWidgetInfo().then(data => {
						this.sVersion = data;
						this.detectUpgrade(info); // 发起更新
					});
					return
				}
				this.sVersion = sVersion;
				this.detectUpgrade(info);
			},
			checkVersion (oldVersion, newVersion) {
				const oldV = oldVersion.split('.')
				const newV = newVersion.split('.')
				try{
					for (let i = 0; i < newV.length; i++) {
						let oNum = oldV[i] - 0
						let nNum = newV[i] - 0
						if (nNum == oNum) {}
						else if (nNum > oNum) {
							return true
							break
						} else if (nNum < oNum) {
							return false
							break
						}
					}
				}catch(e){
					return false
				}
				return false
			},
			detectUpgrade (info) {
				/*
				 * 更新类型
				 * patch: 热更新
				 * forceall: 安装包下载
				*/
				let checkVersion = this.checkVersion(this.sVersion,info.version)
				if (!checkVersion) {
					this.updateText = '当前版本为最新版本' + this.sVersion
					this.upgrade = 0
					return
				}
				//需要升级
				let updateUrl = ""
				let downloadUrl = ""

				if (this.platform == "android") {
				  updateUrl = info.url
				} else {
				  updateUrl = info.url
				}
        this.AppDownload(updateUrl)
				// if (info.method == 'all'||info.method == 'forceall') {
				// 	this.AppDownload(updateUrl)
				// 	return
				// } else {
				// 	this.AppUpdate(updateUrl)
				// }
			},
			AppUpdate (url) {
				this.updateText = '正在下载更新文件...'
        console.log(this.updateText);
				const downloadTask = uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode === 200) {
							this.updateText = '下载成功，正在安裝...'
							plus.io.resolveLocalFileSystemURL(res.tempFilePath, entry => {
								entry.file(fs => {
									this.installWgt(res.tempFilePath).then(e => {
										entry.remove()
									})
								})
							})
							return
						}
						this.updateText = '下载失败，请检查网络'
						uni.showToast({
							title: '下载失败，请检查网络',
							icon: 'none'
						});
					},
					fail: () => {
						this.updateText = '下载失败，请检查网络'
						uni.showToast({
							title: '下载失败，请检查网络',
							icon: 'none'
						});
					}
				});
				downloadTask.onProgressUpdate((res) => {
					this.changeUpgrade(res.progress)
				});
			},
			AppDownload (updateUrl) {
        console.log(updateUrl);
				if (this.platform == 'ios') {
					plus.runtime.openURL(updateUrl)
					return
				}
        this.updateText = '正在下载更新文件...'
				var dtask = plus.downloader.createDownload( updateUrl, {}, ( d, status ) => {
					// 下载完成
					if ( status == 200 ) {
            this.updateText = '下载成功，正在尝试安裝...'
						let file = plus.io.convertLocalFileSystemURL(d.filename)
						uni.setStorageSync('updateCache',file)
						plus.cache.clear();
						plus.runtime.install(file,{},(res) => {
							// 成功回调
						},function(error){
							uni.showToast({
								title: '安装失败',
								duration: 1500
							});
						})
					} else {
						 uni.showToast({
							title: '更新失败',
							duration: 1500
						 });
					}    
				});  
				dtask.addEventListener( "statechanged", (res)=>{
					this.upgrade = parseInt((res.downloadedSize / res.totalSize) * 100)
				}, false );
				dtask.start();
			},
			installWgt (path) {
				return new Promise(resolve => {
					plus.runtime.install(path, {}, () => {
						this.updateText = '更新成功';
						this.upgrade = parseInt(100)
						uni.$showModal.dialog({
							title: '提示',
							content: '更新完成',
							showCancel: false,
							success: res => {
								plus.runtime.restart()
							}
						})
						resolve()
					}, e => {
						this.updateText = '安装失败'; 
						this.upgrade = 0
						plus.nativeUI.alert("安装失败["+e.code+"]："+e.message); 
						resolve()
					})
				})
			},
			getWidgetInfo() {
				return new Promise(resolve => {
					plus.runtime.getProperty(plus.runtime.appid, wgtinfo => {
						resolve(wgtinfo.version);
					});
				});
			},
			changeUpgrade (progress) {
				this.upgrade = parseInt(progress)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.update {
		&-logo {
			width: 160rpx;
			height: 160rpx;
			margin: 250rpx auto 60rpx auto;
			text-align: center;
			margin: 50rpx auto 60rpx auto;
			.img{
				width: 100%;
				height: 100%;
			}
		}
		&-prog-wrap{
			padding: 50rpx 40rpx;
		}
		&-title {
			display: block;
			width: 100%;
			margin-bottom: 30rpx;
			text-align: center;
		}
	}
</style>
